<template>
    <header>
        <div class="container">
            <div class="logo">
                <img src="../../assets/img/musicLogo.png" alt="">
                <p>嘉晨音乐</p>
            </div>
            <ul class="nav">
                <li 
                    v-for="(item, index) of routerNav" 
                    :key='item.title'
                    @click="toRouterPath(item.routerPath, index)"
                    :class="item.className"
                >{{item.title}}</li>
            </ul>
            <div class="search">
                <el-icon class="serach-icon">
                    <search />
                </el-icon>
                <input 
                    type="text" 
                    placeholder="音乐/视频/电台/用户" 
                    v-model="searchContent"
                    @keydown.enter="keydownSearch"
                />
            </div>
            <div class="login" @click="handlerLoginDialog" v-if="!login_status">
                登录
            </div>
            <div class="head-portrait" v-if="login_status" ref="head_portrait">
                <img :src="$store.state.userInfo.avatarUrl" />
                <i class="make"></i>
                <ul class="user-router">
                    <li 
                        v-for="(item, index) of userNav" 
                        :key="item.title"
                        @click="toRouterPath(item.routerPath)"
                    >

                        <el-icon v-if='index===0'><home-filled /></el-icon>
                        <el-icon v-if='index===1'><medal /></el-icon>
                        <el-icon v-if='index===2'><switch-button /></el-icon>
                        <em>{{item.title}}</em>
                    </li>
                </ul>
            </div>
        </div>
    </header>
</template>

<script setup>

import { getCurrentInstance, inject, ref, reactive } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElMessage } from 'element-plus'
import { nextTick } from "process";
const store = useStore();
const axios = getCurrentInstance().proxy.$http;
const emitter = inject("emitter");
const router = useRouter();

// 处理登录对话框
const handlerLoginDialog = () =>{
    store.commit("MODIFY_LOGIN_DIALOG", !store.state.login_dialog);
}

// 获取登录状态
const login_status = ref(false);
emitter.on("getLoginStatus", async (status) => {
    const { data } = await axios.get('/login/status')
    // console.log(data);
    if(data.data.profile) {
        const { userId, nickname, avatarUrl } = data.data.profile;
        store.commit("USER_INFO", { userId, nickname, avatarUrl });
    }
    
    login_status.value = status;

    // 关闭登录对话框
    store.commit("MODIFY_LOGIN_DIALOG", false);
});

// 检测到页面刷新重新重新调用getLoginStatus方法
window.onpageshow = async function () {
    const loginCheck = document.cookie;
    let arr = loginCheck.split(';')
    let arr1 = [];
    arr.forEach(item => {
        arr1.push(item.split('='));
    })
    let filter = arr1.filter(item => item[0] === " NMTID" || item[0] === ' __csrf');
    if(filter.length) {
        filter.forEach(item => {
            if(item[1] !== '') {
                emitter.emit('getLoginStatus', true)
            }
        })
    } else {
        emitter.emit('getLoginStatus', false)
    }

};

// 用户
const userNav = reactive([
    {title: '我的主页', routerPath: 'home'},
    {title: '我的等级', routerPath: 'level'},
    {title: '退出', routerPath: 'logout'}
])

// 路由导航
const routerNav = reactive([
    {title: '发现音乐', routerPath: 'recommend', className: 'active'},
    {title: '我的音乐', routerPath: 'myMusic', className: ''},
    {title: '关注', routerPath: 'follow', className: ''},
])


// 移出上三角
const move = (index) => {
    routerNav.forEach((item, i) => {
        if(i === index) {
            item.className = 'active';
        }else {
            item.className = '';
        }
    })
}



// 清除所有cookie的方法
function clearCookie(){
    var keys=document.cookie.match(/[^ =;]+(?=\=)/g);
    if (keys) {
        for (var i = keys.length; i--;)
        document.cookie=keys[i]+'=0;expires=' + new Date( 0).toUTCString()
    }
}



// 路由跳转
const toRouterPath = (routerPath, index) => {
    move(index);
    if(routerPath === 'authentication') return open(location.origin + "#" + "user/authentication"); // 打开一个新的table(实名认证)
    if(routerPath === 'logout') {
        axios.get('/logout')
        .then(value => {
            if(value.data.code === 200) {
                clearCookie();
                ElMessage({
                    message: '退出登录成功',
                    type: 'success'
                });
                emitter.emit('getLoginStatus', false)
                nextTick(() => {
                    router.push({ path: '/discover' })
                })
            }
        })
        return 
    }
    router.push({name: routerPath});
}



// search
let searchContent = ref();

const keydownSearch = debounce(async () => {
    router.push({ name: 'search', query: { keyword: searchContent.value } })
    routerNav.forEach(item => item.className = '');
})



function debounce(callback, delay=500) {
    let timeId;
    return function () {
        if(timeId) clearTimeout(timeId);
        timeId = setTimeout(() => {
            callback.call(this); 
        }, delay)
    }
}




</script>

<style lang='less' scoped>
header {
    height: 70px;
    background-color: #242424;
    .container {
        width: 1100px;
        height: 70px;
        margin: 0 auto;
        display: flex;
        flex-direction: row;
        align-items: center;
        display: grid;
        grid-template-columns: 175px 1fr 200px 50px;
        
        .logo{
            display: flex;
            align-items: center;
            user-select: none;
            img{
                width: 40px;
                height: 40px;
                margin-right: 10px;
            }
            p{
                font-size: 18px;
                color: white;
            }
        }
        
        .nav {
            display: flex;
            line-height: 70px;
            li {
                color: white;
                font-size: 15px;
                padding: 0 19px;
                // padding: 0 25px;
                user-select: none;
                &:hover {
                    cursor: pointer;
                    background-color: black;
                }
                &:last-child {
                    position: relative;
                    margin-right: 60px;
                }
            }
            .active{
                background-color: black;
                position: relative;
                &::before{
                    content: "";
                    display: block;
                    width: 0;
                    padding: 0;
                    border-bottom: 7px solid #9b0909;
                    border-left: 7px solid transparent;
                    border-right: 7px solid transparent;
                    position: absolute;
                    left: 50%;
                    transform: translateX(-50%);
                    top: 63px;
                }
            }
        }
        .search {
            position: relative;
            height: 32px;
            width: 160px;
            line-height: 36px;
            background-color: white;
            border-radius: 20px;
            padding-left: 10px;
            .serach-icon {
                color: #ccc;
                font-size: 15px;
            }
            input {
                position: absolute;
                top: 50%;
                transform: translateY(-50%);
                width: 75%;
                border-radius: 20px;
                padding: 0 10px;
                height: 30px;
                border: none;
                outline: none;
                font-size: 12px;
            }
        }
        .login {
            color: #ccc;
            font-size: 13px;
            margin-left: 20px;
            user-select: none;
            cursor: pointer;
            &:hover {
                color: white;
                text-decoration: underline;
            }
        }

        .head-portrait {
            width: 30px;
            height: 100%;
            border-radius: 50%;
            margin-left: 15px;
            position: relative;
            img {
                width: 100%;
                height: 30px;
                border-radius: 50%;
                position: absolute;
                top: 50%;
                transform: translateY(-50%);
            }
            .make {
                width: 0;
                height: 0;
                border-left: 7px solid transparent;
                border-bottom: 7px solid #353535;
                border-right: 7px solid transparent;
                left: 50%;
                top: 50px;
                position: absolute;
                transform: translateX(-50%);
                display: none;
            }
            
            .user-router {
                padding: 0;
                margin: 0;
                position: absolute;
                left: 50%;
                top: 57px;
                transform: translateX(-50%);
                width: 158px;
                background-color: #353535;
                display: none;
                z-index: 2;
                li {
                    user-select: none;
                    height: 34px;
                    width: 100%;
                    line-height: 34px;
                    cursor: pointer;
                    &:hover {
                        background-color: #474747;
                    }
                    .el-icon {
                        font-size: 13px;
                        color: white;
                        margin-top: 6px;
                        margin-left: 30px;
                        margin-right: 10px;
                    }
                    em {
                        text-align: center;
                        color: rgb(206, 202, 202);
                        font-size: 13px;
                    }
                }
            }
            &:hover .make,
            &:hover .user-router {
                display: block;
            }
        }
    }
}
</style>